using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace EaMon
{
    public partial class MainForm : Form
    {
        private EventLogMonitor monitor;
        private bool balloonTipVisible;
        private Timer timer;

        public MainForm()
        {
            InitializeComponent();
            notifyIcon.Text = "eamon";
            monitor = new EventLogMonitor();
            timer = new Timer();
            timer.Interval = 10000;
            HookEvents();
        }

        private void HookEvents()
        {
            Load += HideForm;
            Resize += HideForm;
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            monitor.EventLogNewEntryWritten += NewEntryWritten;
            notifyIcon.BalloonTipShown += BalloonTipShown;
            notifyIcon.BalloonTipClicked += delegate(object sender, EventArgs e) { ShowEventLog(); };
            notifyIcon.BalloonTipClosed +=delegate(object sender, EventArgs e) { balloonTipVisible = false; };
            timer.Tick += delegate(object sender, EventArgs e) { balloonTipVisible = false; };
        }

        private void BalloonTipShown(object sender, EventArgs e)
        {
            timer.Stop();
            timer.Start();
            balloonTipVisible = true;
        }

        private void NewEntryWritten(string message)
        {
            lock (this)
            {
                if (!balloonTipVisible)
                {
                    notifyIcon.ShowBalloonTip(10000, "Event Log Error", message, ToolTipIcon.Error);
                }
            }
        }

        private static void ShowEventLog()
        {
            ProcessStartInfo info = new ProcessStartInfo("eventvwr");
            Process.Start(info);
        }

        private void HideForm(object sender, EventArgs e)
        {
            Visible = false;
            Hide();
        }
    }
}